package com.cskaoyan.typehandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.*;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//简单的预编译的过程
//Preparing:insert into cskaoyan_user (username,password,age,gender) values (#{username},#{password},#{age},#{gender})
//Parameters: jingtian,niupi,25,male
@MappedTypes(Integer[].class)       //映射的Java类型
@MappedJdbcTypes(JdbcType.VARCHAR)  //映射的数据库类型
public class IntegerArrayTypeHandler extends BaseTypeHandler<Integer[]> {
    ObjectMapper objectMapper = new ObjectMapper();
    /**
     * 输入映射过程的方法
     * @param index 参数序号 第几个参数
     * @param integers 为预编译的Sql语句提供的参数 → 将第三个参数转换成数据库中能够接收的类型 👉 在这里就是转换为String
     */
    @SneakyThrows
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int index, Integer[] integers, JdbcType jdbcType) throws SQLException {
        //Integer[] 👉 String
        String value = objectMapper.writeValueAsString(integers);
        preparedStatement.setString(index,value); //Jdbc的代码
    }

    /**
     * 输出映射的过程 Varchar 👉 String 👉 Integer[]
     * 先获得查询结果
     */
    @Override
    public Integer[] getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        String result = resultSet.getString(columnName);
        return transfer(result);
    }

    @Override
    public Integer[] getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String result = resultSet.getString(columnIndex);
        return transfer(result);
    }

    @Override
    public Integer[] getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String result = callableStatement.getString(columnIndex);
        return transfer(result);
    }

    private Integer[] transfer(String result) {
        if (result == null || "".equals(result)) {
            return new Integer[0];
        }
        Integer[] integers = new Integer[0];
        try {
            integers = objectMapper.readValue(result, Integer[].class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return integers;
    }
}
